<?php
/**
 * Created by PhpStorm.
 * User: 黑盒子
 * Date: 2020/11/16
 * Time: 22:11
 */

namespace app\api\controller;

use app\common\exception\ApiException;
use app\api\common\TokenManager;
use think\Controller;

class Admin extends Controller
{
    public function index()
    {
        return $this->fetch('index/index');
    }

    public function login()
    {
        $name = input('name', '');
        $password = input('password', '');

        if (!$name || !$password) {
            throw new ApiException(['msg' => '请填写账号和密码']);
        }

        $password = $this->getEncodePass($password);

        $admin = \app\api\model\Admin::where('name', $name)->where('password', $password)->find();

        if (!$admin) {
            throw new ApiException(['msg' => '账号或密码错误']);
        }

        $access_token = TokenManager::instance()->genAccessToken($admin['id']);

        return json(['success' => 1, 'access_token' => $access_token]);
    }

    public function changePass(){
        $token = TokenManager::instance();
        $token->check();
        $id = $token->getUid();
        //原密码
        $oldpass = input('oldpass','');
        $password = input('password','');

        $admin = \app\api\model\Admin::get($id);

        if ($this->getEncodePass($oldpass) != $admin['password']) {
            throw new ApiException(['msg' => '旧密码错误']);
        }

        if (strlen($password) < 6 || strlen($password) > 11 ) {
            throw new ApiException(['msg' => '密码长度6-12位']);
        }

        $password = $this->getEncodePass($password);

        $rst = \app\api\model\Admin::update(['password' => $password,'access_token' => '','access_time' => 0], ['id' => $id]);

        if(!$rst){
            throw new ApiException(['msg' => '操作失败']);
        }

        return json(['success' => 1, 'msg' => '操作成功']);
    }

    private function getEncodePass($password)
    {
        return md5(md5($password) . 'resourcemanger');
    }
}